package com.king.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.king.common.lang.Result;
import com.king.entity.MPost;
import com.king.entity.MUser;
import com.king.entity.MUserCollection;
import com.king.entity.MUserMessage;
import com.king.shiro.AccountProfile;
import com.king.util.UploadUtil;
import com.king.vo.UserMessageVo;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RequestMapping("/user")
@Controller
public class MUserController extends BaseController {

    @Autowired
    UploadUtil uploadUtil;

    /**
     * 我的主页
     *
     * @return
     */
    @GetMapping({"/home", "/{id:\\d*}"})
    public String home(@PathVariable(name = "id", required = false) Long id) {
        if (id == null) {
            id = getProfileId();
        }

        MUser user = this.mUserService.getById(id);
        if (user != null) {
            List<MPost> posts = this.mPostService.list(new QueryWrapper<MPost>()
                            .eq("user_id", user.getId())
//                    .gt("created", DateUtil.offsetDay(new Date(), -30))
                            .orderByDesc("created")
            );

            request.setAttribute("user", user);
            request.setAttribute("posts", posts);
        }

        return "/user/home";
    }

    /**
     * 用户中心
     *
     * @return
     */
    @GetMapping("/index")
    public String index() {

        int postCount = this.mPostService.count(new QueryWrapper<MPost>()
                .eq("user_id", getProfileId())
        );
        request.setAttribute("postCount", postCount);

        int collectionCount = this.mUserCollectionService.count(new QueryWrapper<MUserCollection>()
                .eq("user_id", getProfileId())
        );
        request.setAttribute("collectionCount", collectionCount);

        return "/user/index";
    }

    /**
     * 基本设置
     *
     * @return
     */
    @GetMapping("/set")
    public String set() {
        MUser user = this.mUserService.getById(getProfileId());
        request.setAttribute("user", user);
        return "/user/set";
    }

    /**
     * 我的消息
     *
     * @return
     */
    @GetMapping("/message")
    public String messsage() {
        IPage<UserMessageVo> pageData = mUserMessageService.paging(getPage(), new QueryWrapper<MUserMessage>()
                .eq("to_user_id", getProfileId())
                .orderByDesc("created")
        );

        //把消息改成已读状态
        List<Long> ids = new ArrayList<>();
        for (UserMessageVo msg : pageData.getRecords()) {
            ids.add(msg.getId());
        }

        mUserMessageService.updateToReaded(ids);

        request.setAttribute("pageData", pageData);
        return "/user/message";
    }

    @ResponseBody
    @PostMapping("/set")
    public Result doSet(MUser user) {
        if (StrUtil.isBlank(user.getUsername())) {
            return Result.fail("昵称不能为空！");
        }

        int count = this.mUserService.count(new QueryWrapper<MUser>()
                .eq("username", user.getUsername())
                .ne("id", getProfileId())
        );
        if (count > 0) {
            return Result.fail("昵称已被占用！");
        }

        MUser temp = this.mUserService.getById(getProfileId());
        temp.setUsername(user.getUsername());
        temp.setGender(user.getGender());
        temp.setSign(user.getSign());
        temp.setModified(new Date());
        this.mUserService.updateById(temp);

        AccountProfile profile = getProfile();//同步shiro缓存信息
        profile.setUsername(temp.getUsername());
        profile.setSign(temp.getSign());

        SecurityUtils.getSubject().getSession().setAttribute("profile", profile);

        return Result.success().action("/user/set#info");
    }

    @ResponseBody
    @PostMapping("/upload")
    public Result uploadAvatar(@RequestParam(value = "file") MultipartFile file) throws IOException {
        return uploadUtil.upload(UploadUtil.type_avatar, file);
    }

    @ResponseBody
    @PostMapping("/updateAvatar")
    public Result updateAvatar(MUser user) {
        if (StrUtil.isBlank(user.getAvatar())) {
            return Result.fail("头像不能为空！");
        }

        MUser temp = this.mUserService.getById(getProfileId());
        temp.setAvatar(user.getAvatar());
        this.mUserService.updateById(temp);

        AccountProfile profile = getProfile();
        profile.setAvatar(temp.getAvatar());

        SecurityUtils.getSubject().getSession().setAttribute("profile", profile);

        return Result.success().action("/user/set#avatar");
    }

    @ResponseBody
    @PostMapping("/repass")
    public Result updatePassword(String nowpass, String pass, String repass) {
        if (StrUtil.isBlank(nowpass) || StrUtil.isBlank(pass)) {
            return Result.fail("当前密码或新密码不能为空！");
        }

        if (!pass.equals(repass)) {
            return Result.fail("两次输入的密码不一致！");
        }

        String nowPwd = SecureUtil.md5(nowpass);
        MUser user = this.mUserService.getById(getProfileId());
        if (!user.getPassword().equals(nowPwd)) {
            return Result.fail("当前密码不正确！");
        }

        user.setPassword(SecureUtil.md5(pass));
        user.setModified(new Date());
        this.mUserService.updateById(user);

        return Result.success().action("/user/set#pass");
    }

    @ResponseBody
    @GetMapping("/post")
    public Result userPost() {
        IPage page = mPostService.page(getPage(), new QueryWrapper<MPost>()
                .eq("user_id", getProfileId())
                .orderByDesc("created")
        );
        return Result.success(page);
    }

    /**
     * SELECT * FROM m_post where id in(
     * SELECT post_id FROM m_user_collection where user_id = 6
     * ) LIMIT 0,2
     *
     * @return
     */
    @ResponseBody
    @GetMapping("/collection")
    public Result userCollection() {
        IPage page = mPostService.page(getPage(), new QueryWrapper<MPost>()
                .inSql("id", "SELECT post_id FROM m_user_collection where user_id =  " + getProfileId())
        );
        return Result.success(page);
    }
}